console.log('background is running')
// background.js
import rules from './rules.js'

// 获取机器码的本地接口 URL
const LOCAL_MACHINE_ID_URL = 'http://localhost:3333/machine-id'
const LOCAL_SAFE_CONFIG_URL = 'http://localhost:3333/safe-config'
const BASEURL = 'https://boolsurvey.com/ai-api'
let machineId = ''
// 封装方法：检查机器码并更新插件状态
function checkAndUpdatePermissions() {
  // 从 Electron 应用获取机器码
  fetch(LOCAL_MACHINE_ID_URL)
    .then((response) => response.text())
    .then((machineid) => {
      machineId = machineid
      // 从远程 JSON 获取允许的机器码列表
      fetch(`${BASEURL}/tools/check-device-id?key=${machineid}`)
        .then((response) => response.json())
        .then((data) => {
          if (data.code === 0) {
            updatePermissions(data.data, machineId)
          } else {
            updatePermissions(false, machineId)
          }
        })
        .catch((error) => {
          console.error('Error fetching user data:', error)
        })
    })
    .catch((error) => {
      updatePermissions(false, machineId)
      console.error('Error fetching machine ID:', error)
    })
}

// 禁用指定规则集
async function disableRuleset() {
  try {
    await chrome.declarativeNetRequest.updateEnabledRulesets({
      disableRulesetIds: ['ruleset_1'], // 要禁用的规则集ID列表
    })
    console.log('规则集已禁用')
  } catch (error) {
    console.error('禁用失败:', error)
  }
}

// 显示未授权警告（带交互）
function showAuthorizationWarning(tab, machineId) {
  chrome.scripting.executeScript({
    target: { tabId: tab.id },
    func: (machineId) => {
      const warningBox = document.createElement('div')
      warningBox.style =
        'position:fixed;top:20px;right:20px;background:red;color:white;padding:10px;z-index:9999'
      warningBox.innerHTML = `
        <h3>${machineId}</h3>
        <p>你的设备未被授权 </p>
      `
      document.body.appendChild(warningBox)
    },
    args: [machineId],
  })
}

async function loadAndApplyRules() {
  try {
    const response = await fetch(LOCAL_SAFE_CONFIG_URL)
    const rulesRes = await response.json()

    const knownCategories = ['Innovate', 'Marketxcel', 'Sample&bib']
    const isEnabledMap = {
      Innovate: rulesRes.includes('Innovate'),
      Marketxcel: rulesRes.includes('Marketxcel'),
      'Sample&bib': rulesRes.includes('Sample&bib'),
      Other: rulesRes.some((cat) => !knownCategories.includes(cat)), // 只要出现未知类别就启用 Other
    }

    // 过滤出应保留的规则
    // 过滤出应保留的规则
    let newRules = rules
      .filter((rule) => {
        const category = rule.category
        if (knownCategories.includes(category)) {
          return isEnabledMap[category]
        } else {
          return isEnabledMap.Other
        }
      })
      .map(({ category, ...rest }) => rest) // <-- 去掉 category 字段

    console.log(
      '启用的规则: ',
      newRules.map((r) => r.id),
    )

    // 获取已有规则
    const existingRules = await chrome.declarativeNetRequest.getDynamicRules()
    const existingRuleIds = existingRules.map((rule) => rule.id)

    // 更新规则
    chrome.declarativeNetRequest.updateDynamicRules(
      {
        removeRuleIds: existingRuleIds,
        addRules: newRules,
      },
      async () => {
        if (chrome.runtime.lastError) {
          console.error('规则更新出错：', chrome.runtime.lastError)
        } else {
          const existingRules = await chrome.declarativeNetRequest.getDynamicRules()
          console.log('规则已成功更新！', existingRules)
        }
      },
    )
  } catch (error) {
    console.log('error: ', error)
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      setTimeout(() => {
        showAuthorizationWarning(tabs[0], machineId)
      }, 3000)
    })
  }
}

chrome.runtime.onInstalled.addListener(async () => {
  checkAndUpdatePermissions()
  loadAndApplyRules()
})

chrome.runtime.onStartup.addListener(() => {
  loadAndApplyRules()
})

// 检查机器码是否在允许列表中
function checkMachinePermission(userData, machineId) {
  if (userData && userData.user) {
    return userData.user.some((machine) => machine.key === machineId && machine.enbled)
  }
  return false
}

// 更新权限
function updatePermissions(isEnabled, machineId) {
  // if (!isEnabled) {
  //   chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
  //     showAuthorizationWarning(tabs[0],machineId)
  //   })
  //   disableRuleset()
  // }
}

// setTimeout(() => {
//   checkAndUpdatePermissions()
// }, 3000)

let token = ''
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  console.log('request', request)

  if (request.action === 'COUNT') {
    console.log('background has received a message from popup, and count is ', request?.count)
  }

  if (request.action === 'kk-score') {
    // 向当前标签页的 content script 发送消息
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      chrome.tabs.sendMessage(tabs[0].id, { action: 'kkScore', data: request.data })
    })
  }
})
